package com.jueming.miser.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jueming.miser.auth.feign.OrderFeignService;
import com.jueming.miser.auth.interceptor.CartInterceptor;
import com.jueming.miser.auth.service.CartService;
import com.jueming.miser.auth.to.MiserOrderTo;
import com.jueming.miser.auth.to.MiserUserTo;
import com.jueming.miser.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@Service("cartService")
public class CartServiceImpl implements CartService{


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private ThreadPoolExecutor executor;
    @Override
    public R addToCart(MiserOrderTo to) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String wareIdString = to.getWareId().toString();
        String s = (String) cartOps.get(wareIdString);
        MiserOrderTo curTo = JSON.parseObject(s, MiserOrderTo.class);
        if (curTo != null) {
            curTo.setWareCount(curTo.getWareCount() + to.getWareCount());
            if (curTo.getWareCount() == 0) {
                //数量归零则从购物车中删除
                cartOps.delete(wareIdString);
            } else {
                cartOps.put(wareIdString, JSON.toJSONString(curTo));
            }
        } else {
            cartOps.put(to.getWareId().toString(), JSON.toJSONString(to));
        }
        return R.ok("更新订单组成功");
    }

    @Override
    public List<MiserOrderTo> listCart() {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        List<MiserOrderTo> tos = new ArrayList<>();
        for (Map.Entry<Object, Object> item : cartOps.entries().entrySet()) {
            //TODO:json反序列化失败**
//            MiserOrderTo to = JSONObject.parseObject((String) item.getValue(), MiserOrderTo.class);
            tos.add(JSONObject.parseObject((String) item.getValue(), MiserOrderTo.class));
        }

        return tos;

    }

    @Override
    public BoundHashOperations<String, Object, Object> getCartOps() {

        MiserUserTo to = CartInterceptor.toThreadLocal.get();

        return redisTemplate.boundHashOps(to.getUserId().toString());
    }

    @Override
    public R addToCart(Integer wareId, Integer wareCount) {
        MiserOrderTo to = new MiserOrderTo();
        MiserUserTo user = CartInterceptor.toThreadLocal.get();

        to.setWareCount(wareCount);
        to.setWareId(wareId);
        to.setUserId(user.getUserId());
        return addToCart(to);
    }


}
